//	子弹图
import React from 'react';
import { Bullet } from '@antv/g2plot';
import { data } from './mock';
import { getComponentData } from 'src/services/AnalyseManage';
import { WD_TYPE, DL_TYPE } from 'src/pages/AnalyseManage/EditReport/components/EditorDataType/EnumConfig';
import { ChartService, IProps } from 'src/pages/AnalyseManage/EditReport/components/ChartsType/components/ChartService';
import { isNumber } from 'src/libs/utils';

export default class BulletChart extends ChartService {
	state = {
		chartEl: null,
		data: data,
		eventToken: [],
		dependencies: [],	//	图表联动参数
		isRender: false
	};

	initEvent = async () => {
		const newData = await this.getConditionData();
		this.setState( { data: newData }, () => {
			const bullet = new Bullet( this.props.id, this.getConfig() );
			bullet.render();
			this.setState( {
				chartEl: bullet,
				isRender: true
			} );
		} );
	};

	getSnapshotBeforeUpdate( prevProps: Readonly<IProps>, prevState: Readonly<{ dependencies: any }> ): any | null {
		let { config } = this.props;
		let changeObj = Object.create( null );

		//	判断数据字段是否变化了
		if ( JSON.stringify( prevProps.config.data ) !== JSON.stringify( config.data ) ||
			JSON.stringify( this.state.dependencies ) !== JSON.stringify( prevState.dependencies ) ) {
			changeObj.needDataChange = true;
		}

		//	判断样式是否改变
		if ( JSON.stringify( prevProps.config.style ) !== JSON.stringify( config.style ) ) {
			changeObj.needStyleChange = true;
		}

		// 判断bulletType是否改变，需重新render
		if ( prevProps.config.data.bulletType !== config.data.bulletType ) {
			changeObj.needRender = true;
		}

		return changeObj;
	}

	async componentDidUpdate( prevProps: Readonly<IProps>, prevState: Readonly<{}>, snapshot?: any ) {
		if ( snapshot.needStyleChange ) {
			this.state.chartEl.update( this.getConfig() );
		}
		if ( snapshot.needDataChange ) {
			// 更新数据
			const newData = await this.getConditionData();
			// 重新渲染
			if ( snapshot.needRender ) {
				this.setState( { data: newData, chartEl: null }, () => {
					document.getElementById( this.props.id ).innerHTML = '';
					const bullet = new Bullet( this.props.id, this.getConfig() );
					bullet.render();
					this.setState( {
						chartEl: bullet,
					} );
				} );
				return;
			}
			this.setState( { data: newData }, () => {
				this.state.chartEl.update( this.getConfig() );
				this.state.chartEl.changeData( this.formatData() );
			} );
		}
	}

	getConfig = (): any => {
		let { style, data: dataConfigs } = this.props.config;
		// console.log( dataConfigs );
		const formatData = this.formatData();
		return {
			data: formatData,
			layout: dataConfigs.bulletType,
			measureField: formatData[0].measures,
			rangeField: 'ranges',
			targetField: formatData[0].target,
			xField: 'title',
			color: {
				range: style.chartRangeColor || '#f0fbff',
				measure: style.chartMeasureColor || '#0DD0D9',
				target: style.chartTargetColor || '#0DD0D9',
			},
			// 设置轴边距
			appendPadding: [
				style.chartTopPadding || 0,
				style.chartRightPadding || 0,
				style.chartBottomPadding || 0,
				style.chartLeftPadding || 0
			],
			padding: 'auto',
			legend: style.isShowLegend === true ? {
				custom: true,
				position: style.legendPosition,
				items: [
					{
						value: '实际值',
						name: '实际值',
						marker: { symbol: 'square', style: { fill: style.chartMeasureColor || '#0DD0D9', r: 5 } },
					},
					{
						value: '目标值',
						name: '目标值',
						marker: { symbol: 'line', style: { stroke: style.chartTargetColor || '#0DD0D9', r: 5 } },
					},
				],
				itemName: {
					style: {
						fill: style.legendFontColor,
						fontSize: style.legendFontSize,
						fontFamily: style.legendFontFamily,
						fontWeight: style.legendFontBold ? 'bold' : 'normal',
						fontStyle: style.legendFontItalic ? 'italic' : 'normal',
					},
				},
			} : false,
			tooltip: this.getToolTipConfig( style ),
			xAxis: {
				line: null,
			},
			yAxis: false,
			label: this.getLabelConfig( style ),
			// 设置标签
			point: this.getPointOptions( style ),
		};
	};

	// 数据处理
	formatData = () => {
		let { style } = this.props.config;
		let data = JSON.parse( JSON.stringify( this.state.data ) );
		if ( style.isShowLabelText ) {
			if ( style.chartCustomText ) {
				data.forEach( item => {
					item.title = style.chartCustomText;
				} );
			}
		} else {
			data.forEach( item => {
				item.title = '';
			} );
		}
		let result = data.map( item => {
			let obj = {
				title: item.title,
				ranges: item.ranges,
				measures: item.measures.field,
				target: item.target.field,
			};
			obj[ item.measures.field ] = [ item.measures.value ];
			obj[ item.target.field ] = item.target.value;
			return obj;
		} );
		return result;
	}

	getLabelConfig = ( style ) => {
		return style.isShowLabelData
			? {
				measure: {
					position: 'middle',
					style: {
						fontFamily: style.labelFontFamily || 'none',
						fontSize: parseInt( style.labelFontSize || 15 ),
						fontWeight: style.labelFontBold ? 'bold' : 'normal',
						fontStyle: style.labelFontItalic ? 'italic' : 'normal',
						fill: style.labelFontColor || '#fff',
					},
					content: () => {
						let { value, precision = '', dataUnit = '' } = this.state.data[0].measures;
						//	@ts-ignore
						value = isNumber( precision ) ? value.toFixed( precision ) : value;
						return `${value}${dataUnit}`;
					},
				},

			  }
			: null;
	};

	// 设置提示config
	getToolTipConfig = ( style ) => {
		return style.isShowToolTip
			? {
				showContent: true,
				// 设置toolTip相关样式
				domStyles: {
					'g2-tooltip-list-item': {
						fontSize: `${style.tooltipFontSize || '12'}px`,
						color: style.tooltipFontColor,
						fontFamily: style.tooltipFontFamily,
						fontWeight: style.tooltipFontBold ? 'bold' : 'normal',
						fontStyle: style.tooltipFontItalic ? 'italic' : 'normal',
					},
					'g2-tooltip-title': {
						fontSize: `${style.tooltipFontSize || '12'}px`,
						color: style.tooltipFontColor,
						fontFamily: style.tooltipFontFamily,
						fontWeight: style.tooltipFontBold ? 'bold' : 'normal',
						fontStyle: style.tooltipFontItalic ? 'italic' : 'normal',
					},
				},
				formatter: ( datum ) => {
					//	获取tooltip信息，再去从state.data中映射出来dataUnit和precision
					let data =  this.state.data[0];
					let key = '';
					let { mKey, tKey } = datum;
					if( !mKey && !tKey ) return { name: '暂无数据', value: '暂无数据' };
					let keyInDatum = mKey ? 'mKey' : 'tKey';	//	获取tooltip信息中的key名
					if( this.state.data[0].measures.field === datum[keyInDatum] ) {
						key = 'measures';
					}
					if( this.state.data[0].target.field === datum[keyInDatum] ) {
						key = 'target';
					}
					let precision = data[key].precision || '';
					let dataUnit = data[key].dataUnit || '';
					let value = datum[ datum[ keyInDatum ] ];
					value = isNumber( precision ) ? value.toFixed( precision ) : value;
					return { name: datum[ keyInDatum ], value: `${value}${dataUnit}` };
				}
			}
			: {
				showContent: false,
				domStyles: null,
			};
	};

	// 设置标签样式
	getPointOptions = ( style ) => {
		let config = {
			size: style.chartLabelMarkSize || 5,
			shape: style.chartLabelMarkType
				? style.chartLabelMarkType === 'hollowCircle'
					? 'circle'
					: style.chartLabelMarkType
				: 'circle',
			style: {
				fill: '#5B8FF9',
				stroke: '#5B8FF9',
				lineWidth: 2,
			},
		};
		// 如果是空心圆需要填充白色
		if ( style.chartLabelMarkType === 'hollowCircle' ) {
			config.style.fill = 'white';
		}
		return style.isShowLabelData ? config : null;
	};

	// 获取数据
	async getConditionData() {
		const { data: dataConfigs } = this.props.config;
		if (
			dataConfigs.chartTargetColumns &&
			dataConfigs.chartTargetColumns.length > 0 &&
			dataConfigs.chartMeasureColumns &&
			dataConfigs.chartMeasureColumns.length > 0
		) {
			const itemInfo = ( v, orderType?, desc? ) => {
				return {
					aggregateType: v.modelType === DL_TYPE ? v.aggregateType : '', //	度量的聚合类型
					formatType: v.modelType === WD_TYPE ? v.formatType : '', // 维度的聚合类型v.
					alias: v.title.trim(),
					dataType: v.dataType,
					frontendId: '',
					id: v.name,
					orderType: orderType || v.orderType, // 排序方式
					quota: v.modelType === WD_TYPE ? 'WD' : 'DL',
					symbol: '',
					type: v.type,
					value: '',
					dataUnit: v.dataUnit || '',
					precision: v.precision
				};
			};
			const x = dataConfigs.chartTargetColumns.map( ( v ) => {
				if ( v.dataType === 'datetime' ) {
					return itemInfo( v, 'ASC' );
				}
				return itemInfo( v );
			} );

			const y = dataConfigs.chartMeasureColumns.map( ( v ) => {
				return itemInfo( v );
			} );

			/* const category = dataConfigs.chartLineColorColumns ? dataConfigs.chartLineColorColumns.map( ( v ) => {
				return itemInfo( v );
			} ) : []; */

			// const conditions = this.props.config.data.filterFields ? this.props.config.data.filterFields.map( v => v.filterConditions ).flat() : [];
			// 内部筛选 condition
			const filterFieldCondition = this.props.config.data.filterFields
				? this.props.config.data.filterFields.map( ( v ) => v.filterConditions ).flat()
				: [];

			// 筛选组件的 condition
			let filterCompConditions = this.props.config.data.filterConditions || {};
			let newFilterCompConditions = [];
			Object.keys( filterCompConditions ).forEach( ( key ) => {
				newFilterCompConditions = newFilterCompConditions.concat( filterCompConditions[key] );
			} );

			const request = {
				dataConfig: {
					dataModel: {
						pageId: this.props.pageId,
						tableName: this.props.config.data.tableCode,
						x: x,
						y: y,
						// category: category,
						conditions: filterFieldCondition.concat( this.state.dependencies, newFilterCompConditions )
					},
					needAutoRefresh: true,
					tableType: 'progress',
				},
				type: 'bar',
				tenantCode: this.props.tenantCode
			};

			let pageResponse = await getComponentData( request );
			if ( pageResponse.data && pageResponse.data.success ) {
				const { rows } = pageResponse.data.data;
				if ( rows.length ) {
					return rows.map( item => {
						item.ranges = [ parseInt( item.ranges ) ];
						return item;
					} );
				}
			}
		}

		return data;
	}

	render() {
		return <div id={this.props.id} style={{ height: '100%' }}></div>;
	}
}
